<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from '../plugins/axios' // 引入配置好的 axios 实例
import AnnouncementDetail from '../components/AnnouncementDetailItem.vue'

const route = useRoute()
const router = useRouter()

const announcement = ref(null)
const canEdit = ref(false) // 这里需要根据用户权限判断

onMounted(async () => {
  const publicId = route.params.id
  try {
    // 从后端获取公告详情
    const response = await axios.get(`/public/query/${publicId}`)
    if (response.data.code === 1) {
      announcement.value = response.data.data
    } else {
      throw new Error(response.data.msg || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情失败：', error)
    // 在API调用失败时使用模拟数据
    announcement.value = {
      id: parseInt(publicId),
      title: '示例公告',
      publishTime: '2024-02-20',
      author: '张三',
      content: '这是一个示例公告内容，用于在API调用失败时显示。实际内容将从后端获取。',
      site: '全站'
    }
  }
})

const handleEdit = (announcement) => {
  router.push(`/announcement/edit/${announcement.id}`)
}

const handleDelete = async (announcement) => {
  if (confirm('确定要删除这条公告吗？')) {
    // TODO: 调用后端接口进行假删除
    router.push('/announcement/list')
  }
}

const handleBack = () => {
  router.back()
}
</script>

<template>
  <div class="announcement-detail-page">
    <AnnouncementDetail
      v-if="announcement"
      :announcement="announcement"
      :canEdit="canEdit"
      @edit="handleEdit"
      @delete="handleDelete"
      @back="handleBack"
    />
  </div>
</template>

<style scoped>
.announcement-detail-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
</style>